package com.umpay.controller.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.umpay.dto.UMFRequest;
import com.umpay.dto.UMFResponse;
import com.umpay.dto.UMFResponse.Message;
import com.umpay.dto.UMFResponse.Message.Meta;

public abstract class AbstractController {

    private static final Logger log = LogManager.getLogger(AbstractController.class);

    /**
     * 获取响应体（无links情况）
     * 
     * @Description (TODO这里用一句话描述这个方法的作用)
     * @param map
     * @return
     */
    protected static Message getUMFResponseBody(Map<String, Object> map) {
        Message body = new Message();
        if (!CollectionUtils.isEmpty(map)) {
            String retCode = StringUtils.trim((String) map.get(UMFResponse.MESSAGE_META_RETCODE));
            String retMsg = StringUtils.trim((String) map.get(UMFResponse.MESSAGE_META_RETMSG));
            if (StringUtils.isNotEmpty(retCode) || StringUtils.isNotEmpty(retMsg)) {
                body.setMeta(new Meta(retCode, retMsg));
            }
            Object obj = map.get(UMFResponse.MESSAGE_DATA);
            body.setData(obj);
        }
        return body;
    }

    protected static String getJsonString(Object obj) {
        String result = "";
        try {
            result = new ObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 获取请求体
     * 
     * @Description (TODO这里用一句话描述这个方法的作用)
     * @param request
     * @return
     */
    protected <T> T getReqMessage(HttpServletRequest request) {
        UMFRequest<T> umfRequest = (UMFRequest<T>) request.getAttribute(UMFRequest.REQUEST);
        log.info(String.format("接受请求参数[%s]", umfRequest));
        return umfRequest.getMessage();
    }

}
